package com.essc.serviceImpl;

import com.essc.mapper.GoodsMapper;
import com.essc.mapper.UserMapper;
import com.essc.pojo.Goods;
import com.essc.pojo.User;
import com.essc.service.GoodsService;
import com.essc.utils.JsonResult;
import com.essc.utils.PageResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;

@Service
public class GoodsServiceImpl implements GoodsService {
    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private UserMapper userMapper;
    /*添加商品，上传商品图片*/
//    @Override
//    public JsonResult addGoodsAndUploadImage
//    (HttpSession session,Goods goods, String username, MultipartFile file) {
//        //这边明晓打算是用token去拿到uid，现在只能这么写，后面交给明晓去改了
//        /*if(session.getAttribute("uid")==null){
//            return new JsonResult(201,"会话超时，请重新登录");
//        }*/
//        /*if (goods.getUid()==null){
//            return new JsonResult(201,"会话超时，请重新登录");
//        }*/
//        if (goods.getGname()==null || goods.getGname().equals("")){
//            return new JsonResult(202,"商品名称必须填写");
//        }
//        if (file.isEmpty()){
//            return new JsonResult(203,"请选择上传文件");
//        }
//        if (file.getSize()>1024*1024*50){
//            return new JsonResult(204,"上传文件大于50M");
//        }
//        //获取上传的文件名
//        String filename = file.getOriginalFilename();
//        //获取文件名称的后缀
//        int index = filename.lastIndexOf(".");
//        String suffix = filename.substring(index);
//        //文件的前缀用当前系统时间毫秒值
//        long timeMillis = System.currentTimeMillis();
//        //新文件名=前缀+后缀
//        String newFileName = timeMillis+suffix;
//        //在项目空间设置一个路径，开发一般是放在服务器
//        String path = session.getServletContext().getRealPath("upload");
//        //完整路径
//        String fullPath = path+"\\"+username;
//        //检测上面的路径是否存在
//        File file1 = new File(fullPath);
//        if (!file1.exists()){
//            //不存在，则创建这个目录
//            file1.mkdir();
//        }
//        //文件目录（本地项目）字符串
//        String filePath = fullPath+"\\"+newFileName;
//        System.out.println("文件路径==========================================="+filePath);
//        //用File对象描述文件的路径
//        File file2 = new File(filePath);
//        //上传文件
//        try {
//            file.transferTo(file2);
//            goods.setPic(filePath);
//            //session.setAttribute("pic",newFileName);
//        }catch (IOException e){
//            e.printStackTrace();
//            return new JsonResult(205,"上传失败");
//        }
//
//        int row = goodsMapper.addGoods(goods);
//        if (row != 1){
//            return new JsonResult(206,"增加失败");
//        }
//        String url = "localhost:8060/upload/"+username+"/"+newFileName;
//        return new JsonResult(200,"增加成功",url);
//    }

    @Override
    public JsonResult findGoodsInfoByPage(Integer pageNum, Integer pageSize) {
        //设置分页
        PageHelper.startPage(pageNum,pageSize);
        //获取所有的商品信息
        List<Goods> goodsList = goodsMapper.findAllGoodsInfo();
        PageInfo<Goods> goodsPageInfo = new PageInfo<>(goodsList);
        List<Goods> goodsList1 = goodsPageInfo.getList();
        return new JsonResult(200,"查询成功",goodsList1);
    }
    @Override
    public JsonResult goodsNum() {
        int num = goodsMapper.goodsNum();
        if (num==0){
            return new JsonResult(201,"找不到商品信息");
        }
        return new JsonResult(200,"查询条数返回成功",num);
    }

    //根据cid查询出对应（某一种商品分类）的商品，并分页
    @Override
    public JsonResult findGoodsInfoByPageAndCid(Integer cid,Integer pageNum, Integer pageSize) {
        //设置分页
        PageHelper.startPage(pageNum,pageSize);
        //根据cid查询某一分类的所有商品信息,其实是一个Catalog对象，里面有List<Goods>属性
        List<Goods> goodsInfoByPageAndCid = goodsMapper.findGoodsInfoByPageAndCid(cid);
        //获得分页信息
        PageInfo<Goods> goodsPageInfo = new PageInfo<>(goodsInfoByPageAndCid);
        List<Goods> goodsList1 = goodsPageInfo.getList();
        return new JsonResult(200,"查询成功",goodsList1);
    }

    //查询分类商品条数
    @Override
    public JsonResult goodsNumByCid(int cid) {
        int num = goodsMapper.goodsNumByCid(cid);
        if (num==0){
            return new JsonResult(201,"找不到商品信息");
        }
        return new JsonResult(200,"查询条数返回成功",num);
    }


    @Override
    //添加商品
    public JsonResult addGood(Goods good) {
        int row=goodsMapper.addGood(good);
        int gid=good.getGid();
        int weight=gid/100+1;
        goodsMapper.insertGoodsWeight(gid,weight);
        if (row!=1){
            return new JsonResult(201,"添加商品失败");
        }
        return new JsonResult(200,"添加商品成功");
    }

    @Override
    public JsonResult uploadImage(MultipartFile file, String username, HttpSession session) {
        if(file.isEmpty()){
            return new JsonResult(201,"文件找不到");
        }
        String fileName = file.getOriginalFilename(); //原文件名
        //获取文件名后缀
        int index = fileName.lastIndexOf(".");//查询从后往前的第一个.  返回从前往后到这个点的下标
        String suffix = fileName.substring(index);
        //用当前系统时间毫秒值 生成一个新的文件名
        long time=System.currentTimeMillis();
        String newFileName=time+suffix;//新文件名
        //从webapp路径去找upload文件夹，找不到则添加一个名为upload的文件夹
        String path = session.getServletContext().getRealPath("upload");
        String fullPath=path+"\\"+username;
        File file1=new File(fullPath);
        if (!file1.exists()){
            file1.mkdir();
        }
        String filePath=fullPath+"\\"+newFileName;
        System.out.println("filepath:"+filePath);
        //使用file2对象描述文件的路径
        File file2=new File(filePath);
        try {
            file.transferTo(file2);
        }
        catch (IOException e) {
            e.printStackTrace();
        }

        String url="http://localhost:8080/upload/"+username+"/"+newFileName;
        session.setAttribute("image",url);
        return new JsonResult(200,"上传成功",url);
    }

    @Override
    public JsonResult findGoodById(Integer gid) {
        if(gid==null){
            throw new RuntimeException("id不能为空");
        }
//        使用持久层对象调用持久层方法
        Goods good = goodsMapper.findGoodById(gid);
        User userinfo = userMapper.findUserById(good.getUid());
        good.setUsername(userinfo.getUsername());
        return new JsonResult(200,"查找成功",good);

    }

    @Override
    public JsonResult findGoodByUid(int uid) {
        List<Goods> goods = goodsMapper.findGoodByUid(uid);
        if (goods==null){
            return new JsonResult(200,"该用户没有发布过商品");
        }
        return new JsonResult(200,"查找成功",goods);
    }

    //搜索框模糊查询商品
    @Override
    public JsonResult findGoodsBySelect(String select,Integer pageNum, Integer pageSize) {
        //设置分页
        PageHelper.startPage(pageNum,pageSize);
        //获取模糊查询的商品
        List<Goods> listSelect=goodsMapper.findGoodsBySelect(select);
        PageInfo<Goods> goodsPageInfo = new PageInfo<>(listSelect);
        int totalSize=(int)goodsPageInfo.getTotal();
        List<Goods> listSelect1 = goodsPageInfo.getList();
        PageResult pageResult = new PageResult(pageNum,pageSize,totalSize,listSelect1);
        return new JsonResult(200,"查询成功",pageResult);
    }

}
